//
//  XTWelcomeVC.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/13.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

class XTWelcomeVC: UIViewController {

    //懒加载控件
    
    //背景图片
    lazy private var bgImgView : UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    //添加头像
    lazy private var headImgView : UIImageView = {
        let view = UIImageView(image: UIImage(named:"avatar_default_big"))
        view.layer.cornerRadius = 42.5
        view.layer.masksToBounds = true
        
        return view
    }()
    
    
    //添加欢迎文字
    lazy private var textLabel:UILabel = {
    let label = UILabel()
        if let name = XTUserAccountViewModel.sharedUserAccount.userAccount?.name{
            
            let text = name + " 欢迎回来"
            label.text = text
        }else{
            label.text = "欢迎回来"
        }
        
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        label.numberOfLines = 0
    
        return label
    }()
    
    //自定义view
    override func loadView() {
        view = bgImgView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }

    override func viewDidAppear(animated: Bool) {
        startAnimation()
    }
    
    
    //添加子视图、添加约束
    private func setupUI(){
            view.addSubview(headImgView)
            view.addSubview(textLabel)
        
        headImgView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view)
            make.top.equalTo(view).offset(200)
        }
        
        textLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImgView.snp_bottom).offset(10)
            make.centerX.equalTo(view)
        }
    }
    
    //通过改变约束的方式实现动画效果
    private func startAnimation(){
    headImgView.snp_updateConstraints { (make) -> Void in
        make.top.equalTo(view).offset(100)
        }
        
        //usingSpringWithDamping : 弹簧阻尼 0～1
        //initialSpringVelocity：弹簧的初始速度
        textLabel.alpha = 0
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in
            //重新加载子视图布局
             self.view.layoutSubviews()
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    //动画内容
                    self.textLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        //动画执行结束后调用的方法
                        //切换window的根视图
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: nil)
                })
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
